package com.niiwoo.civet.trade.service.local.newRefund.notify.mq;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;
import com.niiwoo.civet.trade.service.local.newRefund.notify.RefundNotifyHandle;
import com.niiwoo.civet.trade.service.local.newRefund.notify.dto.RefundNotifyDTO;
import com.niiwoo.civet.trade.service.local.newRefund.notify.dto.RefundNotifyHandleResult;
import com.niiwoo.tripod.provider.exception.BizException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class MQRefundNotify implements RefundNotifyHandle {
	
	@Autowired
	private RabbitTemplate rabbitTemplate;
	
	@Override
	public RefundNotifyHandleResult handle(RefundNotifyDTO refundNotifyDTO) {
		RefundNotifyHandleResult refundNotifyHandleResult = null;
		
		try {
			// 调用具体的消息处理类构建消息内容
			Object messageObject = bulidParam(refundNotifyDTO);

			// 如果内容为空，直接返回成功（部分消息可能不需要处理，在构建参数的时候直接返回null）
			if (null == messageObject) return new RefundNotifyHandleResult();
			
			log.info("还款流程：{}, 消息内容：{}", refundNotifyDTO.getRefundNotifyEnum().getDesc(), JSONObject.toJSONString(messageObject));
			rabbitTemplate.convertAndSend(refundNotifyDTO.getRefundNotifyEnum().getParam1(), refundNotifyDTO.getRefundNotifyEnum().getParam2(), messageObject);
			log.info("还款流程：{}成功", refundNotifyDTO.getRefundNotifyEnum().getDesc());
			
			refundNotifyHandleResult = new RefundNotifyHandleResult();
		} catch (Exception e) {
            if (e instanceof BizException) {
            	// 异常补偿需要排除不符合业务要求的异常
				if (!"TRD00000".equals(((BizException) e).getErrorCode())) {
                	refundNotifyHandleResult = new RefundNotifyHandleResult(e.getMessage());	
                } else {
                	refundNotifyHandleResult = new RefundNotifyHandleResult();
                }
            } else {
            	refundNotifyHandleResult = new RefundNotifyHandleResult(e.getMessage());
            }
			log.error("还款流程：{}异常，异常原因：{}， 消息内容：{}", e.getMessage(), JSONObject.toJSONString(refundNotifyDTO.getRefundNotifyRecord()), e);
		}
		return refundNotifyHandleResult;
	}
}